//
//  ALPS_ClassifyClickClickAlbumController.m
//  Alps
//
//  Created by dllo on 16/6/8.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ALPS_ClassifyClickClickAlbumController.h"
#import "ALPS_SpecialDetailModel.h"
#import "ALPS_SpecialDetailTableCell.h"
// 播放界面
#import "ALPS_PlayerMainViewController.h"
// 提示框
#import <MBProgressHUD.h>


@interface ALPS_ClassifyClickClickAlbumController ()<UITableViewDelegate, UITableViewDataSource>

/** 头视图数据源字典 */
@property (nonatomic, strong) NSMutableDictionary *headerDataSourceDic;
/** table数据源数组 */
@property (nonatomic, strong) NSMutableArray *tableDataSourceArr;
/** table */
@property (nonatomic, strong) UITableView *tableView;
/** 最大页数 */
@property (nonatomic, assign) NSInteger maxPageNum;
/** 监控当前第几页 */
@property (nonatomic, assign) NSInteger pageNumber;

// 判断当前专辑是否被收藏
@property (nonatomic, assign) BOOL currentAlbumIsCollected;
// 收藏or取消收藏按钮
@property (nonatomic, strong) UIButton *collectButton;
// 空心or红心Img
@property (nonatomic, strong) UIImage *ifCollectedImg;

@end

@implementation ALPS_ClassifyClickClickAlbumController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建tableView
    [self createTable];
    // 获取数据
    [self getData];

    [self setLeftBackButton];
    
}

#pragma mark 数据请求
- (void)getData
{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/album?albumId=%ld&device=iPhone&pageSize=20&source=5&statEvent=pageview%%2Falbum%%402897088&statModule=小编推荐&statPage=tab%%40发现_推荐&statPosition=1&trackId=15946929", self.albumId];
    NSLog(@"%ld", self.albumId);
    [WSSNetTool GetNetByURL:urlString body:nil headers:nil response:WSSJSON success:^(id result) {
        NSDictionary *tempDictionary = result[@"data"];
        self.headerDataSourceDic = tempDictionary[@"album"];
        NSArray *temptableListArray = tempDictionary[@"tracks"][@"list"];
        self.maxPageNum = [tempDictionary[@"tracks"][@"maxPageId"] integerValue];
        for (NSDictionary *dic in temptableListArray)
        {
            ALPS_SpecialDetailModel *model = [[ALPS_SpecialDetailModel alloc] initWithDic:dic];
            [self.tableDataSourceArr addObject:model];
        }
        // 刷新UI
        [self.tableView reloadData];
        // 头视图
        [self createHeaderForTable];
        
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark -- table_UI
- (void)createTable
{
    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000];
    self.navigationItem.title = @"专辑详情";
    
    self.headerDataSourceDic = [NSMutableDictionary dictionary];
    self.tableDataSourceArr = [NSMutableArray array];
    self.pageNumber = 1;

    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_tableView];
    self.tableView.scrollsToTop = YES;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.rowHeight = 100.0;
    
    _tableView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.000];
    
    // 注册
    [self.tableView registerClass:[ALPS_SpecialDetailTableCell class] forCellReuseIdentifier:@"ALPS_SpecialDetailTableCell"];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pageNumber ++;
        [self upForDataByPageNumber:_pageNumber];
    }];
}

#pragma mark -- 头视图UI
- (void)createHeaderForTable
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreeWidth, ScreeHeight / 3)];
    
    // 头视图背景模糊图
    UIImageView *backImgView = [[UIImageView alloc] initWithFrame:headerView.bounds];
    [headerView addSubview:backImgView];
    [backImgView sd_setImageWithURL:[NSURL URLWithString:self.headerDataSourceDic[@"coverOrigin"]]];
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = headerView.bounds;
    [headerView addSubview:effectView];
    
    // 图片
    UIImageView *iconImgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, ScreeWidth / 3, ScreeWidth / 3)];
    iconImgView.backgroundColor = [UIColor grayColor];
    [iconImgView sd_setImageWithURL:[NSURL URLWithString:self.headerDataSourceDic[@"coverOrigin"]]];
    [headerView addSubview:iconImgView];
    
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreeWidth / 3 + 20, 10, ScreeWidth * 2 / 3 - 40, 25)];
    [headerView addSubview:titleLabel];
    titleLabel.text = self.headerDataSourceDic[@"title"];
    
    // 主播
    UILabel *speakerLabel = [[UILabel alloc] init];
    [headerView addSubview:speakerLabel];
    [speakerLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.and.height.equalTo(titleLabel);
        make.top.equalTo(titleLabel.bottom).offset(3);
    }];
    speakerLabel.text = [NSString stringWithFormat:@"主播:%@", self.headerDataSourceDic[@"nickname"]];
    speakerLabel.font = [UIFont systemFontOfSize:14];
    
    // 底部分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.frame.size.height - 8, ScreeWidth, 8)];
    [headerView addSubview:lineView];
    lineView.backgroundColor = [UIColor grayColor];
    
    // 内容简介
    UITextView *introduceTextView = [[UITextView alloc] init];
    [headerView addSubview:introduceTextView];
    [introduceTextView makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(titleLabel);
        make.top.equalTo(speakerLabel.bottom).offset(5);
        make.bottom.equalTo(lineView.top).offset(-5);
    }];
    introduceTextView.text = self.headerDataSourceDic[@"intro"];
    introduceTextView.font = [UIFont systemFontOfSize:14];
    introduceTextView.backgroundColor = [UIColor clearColor];
    introduceTextView.editable = NO; //设置不可编辑
    
    self.tableView.tableHeaderView = headerView;
}

#pragma mark -- 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableDataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_SpecialDetailTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ALPS_SpecialDetailTableCell"];
    ALPS_SpecialDetailModel *model = [self.tableDataSourceArr objectAtIndex:indexPath.row];
    cell.model = model;
    cell.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.000];
    return cell;
}


#pragma mark -- MJ上拉加载数据请求
- (void)upForDataByPageNumber:(NSInteger)pageNum
{
    NSString *urlString = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/v1/album/track?albumId=%ld&device=iPhone&isAsc=true&pageId=%ld&pageSize=20&statEvent=pageview%%2Falbum%%402897088&statModule=小编推荐&statPage=tab%%40发现_推荐&statPosition=1",self.albumId, pageNum];
    [WSSNetTool GetNetByURL:urlString body:nil headers:nil response:WSSJSON success:^(id result) {
        
        NSDictionary *tempDictionary = result[@"data"];
        NSArray *temptableListArray = tempDictionary[@"list"];
        for (NSDictionary *dic in temptableListArray)
        {
            ALPS_SpecialDetailModel *model = [[ALPS_SpecialDetailModel alloc] initWithDic:dic];
            [self.tableDataSourceArr addObject:model];
        }
        //停止刷新:
        [self.tableView.mj_footer endRefreshing];
        if (self.pageNumber == self.maxPageNum) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark -- 点击方法(进入播放界面)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALPS_PlayerMainViewController *playerVC = [[ALPS_PlayerMainViewController alloc] init];
    ALPS_SpecialDetailModel *model = [self.tableDataSourceArr objectAtIndex:indexPath.row];
    playerVC.trackId = model.trackId;
    playerVC.listArr = self.tableDataSourceArr;
    [self.navigationController pushViewController:playerVC animated:YES];
}


#pragma mark -- 添加红心or空心
- (void)addIfCollectedButtonOnNavBar
{
    self.collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    self.collectButton.backgroundColor = [UIColor redColor];
    self.collectButton.frame = CGRectMake(ScreeWidth - 64, 5, 34, 34);
    [self.navigationController.navigationBar addSubview:self.collectButton];
    [self.collectButton addTarget:self action:@selector(didClickedCollectButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    if (self.currentAlbumIsCollected == YES)
    {
        self.ifCollectedImg = [UIImage imageNamed:@"player收藏1"];
    }
    if (self.currentAlbumIsCollected == NO)
    {
        self.ifCollectedImg = [UIImage imageNamed:@"player收藏0"];
    }
    [self.collectButton setImage:[self.ifCollectedImg imageWithRenderingMode:1] forState:UIControlStateNormal];
}

#pragma mark -- 收藏按钮点击方法
- (void)didClickedCollectButton
{
    
    if (self.currentAlbumIsCollected == NO)
    {
        self.ifCollectedImg = [UIImage imageNamed:@"player收藏1"];
        self.currentAlbumIsCollected = YES;
        
        // 添加进数据库
        XRDataBaseTool *dataBaseTool = [XRDataBaseTool shareXRDataBaseTool];
        ALPS_RightTableCellModel *model = [[ALPS_RightTableCellModel alloc] init];
        model.albumId = [[self.headerDataSourceDic objectForKey:@"albumId"] integerValue];
        model.id = [[self.headerDataSourceDic objectForKey:@"albumId"] integerValue];
        model.coverLarge = [self.headerDataSourceDic objectForKey:@"coverLarge"];
        model.title = [self.headerDataSourceDic objectForKey:@"title"];
        model.playsCounts = [[self.headerDataSourceDic objectForKey:@"playTimes"] integerValue];
        model.tracks = [[self.headerDataSourceDic objectForKey:@"tracks"] integerValue];
        [dataBaseTool insertDataWithCourseModel:model];
        
        // 提示框
        MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        textOnlyHUD.mode = MBProgressHUDModeText;
        textOnlyHUD.labelText = @"该专辑加入了收藏";
        [textOnlyHUD hide:YES afterDelay:1.f];
        
    }
    else
    {
        self.ifCollectedImg = [UIImage imageNamed:@"player收藏0"];
        self.currentAlbumIsCollected = NO;
        
        // 取消收藏移除从数据库
        XRDataBaseTool *dataBaseTool = [XRDataBaseTool shareXRDataBaseTool];
        [dataBaseTool delegateDataWithAlbumId:self.albumId];
        
        // 提示框
        MBProgressHUD *textOnlyHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        textOnlyHUD.mode = MBProgressHUDModeText;
        textOnlyHUD.labelText = @"该专辑取消了收藏";
        [textOnlyHUD hide:YES afterDelay:1.f];

    }
    [self.collectButton setImage:[self.ifCollectedImg imageWithRenderingMode:1] forState:UIControlStateNormal];
    
}


#pragma mark -- 视图即将出现隐藏navbar
- (void)viewWillAppear:(BOOL)animated
{
    CGFloat alpha = 0;
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor colorWithRed:245.0  / 255.0 green:100.0 / 255.0 blue:100.0 / 255.0 alpha:1.0]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.navigationController.navigationBar.translucent = YES;
    
    // 根据数据库判断是否已经被收藏了
    XRDataBaseTool *dataBaseTool = [XRDataBaseTool shareXRDataBaseTool];
    NSInteger num = [dataBaseTool isSaveDataInTableWithAlbumId:self.albumId];
    if (num == 0)
    {
        self.currentAlbumIsCollected = NO;
    }
    if (num == 1)
    {
        self.currentAlbumIsCollected = YES;
    }
    
    // 视图即将出现添加收藏按钮
    [self addIfCollectedButtonOnNavBar];
    
}

#pragma mark -------------------- 设置导航栏透明
- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    // 开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 使用color演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    // 渲染上下文
    CGContextFillRect(context, rect);
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    // 结束上下文
    UIGraphicsEndImageContext();
    
    return theImage;
}

#pragma mark -- 视图即将消失变回原来的导航栏
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.hidesBarsOnSwipe = NO;
    
    // 视图即将消失移除收藏按钮
    [self.collectButton removeFromSuperview];
}

#pragma mark -- 开始滚动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.navigationItem.title = @"专辑详情";
}


#pragma mark -- 停止滚动
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.navigationItem.title = @"";
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
